const express = require('express')
const fs = require('fs')
const Blob = require('node:buffer').Blob
const os = require("os")
const path = require('path')
const cors = require('cors')

const app = express()

const PORT = 3000;
const mockURL = `https://img0.baidu.com/it/u=2461447895,2337530915&fm=253&fmt=auto&app=138&f=JPEG?w=387&h=388`;


// 解决CORS
// app.use((req, res, next) => {
//   res.header('Access-Control-Allow-Origin', '*')

//   next()
// })
// app.all("*", (req, res, next) => {
//   res.header("Access-Control-Allow-Origin", "*");
//   next()
// })

app.use(cors({
  origin: '*'
}))

// 设置静态目录
app.use(express.static(path.join(__dirname, 'public')))

app.get("/mock/img/redirect", (req, res) => {
  // res.redirect(mockURL)
  // res.setHeader('Content-Security-Policy', `default-src 'none'; img-src 'self' http://localhost:3000`)
  // res.redirect('/mock/img/blob') // Chrome中直接跳转到https下了

  res.redirect('http://localhost:3000/mock/img/blob')

  // res.redirect(301, '/mock/img/blob') // 永久重定向
})

const redirectPath = path.join(__dirname, './public/AAA.png')
app.get("/mock/img/blob", (req, res) => {
  // 不好使的代码
  // fs.readFile('./public/AAA.png', (err, img) => {
  //   if (err) throw err;
  //   res.send(img)
  // })

  const mimeType = getMimeType(redirectPath)
  res.setHeader('Content-Type', mimeType)
  res.setHeader('Content-Security-Policy', `default-src 'none'; img-src 'self' http://localhost:3000`)
  res.sendFile(redirectPath)
})

app.get("/ip-info", (req, res) => {
  const url = req.url;
  const method = req.method;
  
  const str = `您请求的地址:${url},请求方法:${method}`
  // 设置请求头,解决中文乱码问题
  res.setHeader('Content-Type','text/html;charset=utf-8')
  res.write('ip', 'utf8', () => {
    console.log('ippp', getClientIp(req))
  })

  // 发送数据给客户端和结束请求
  res.end(str)
})

app.get("/xxx/user/menu", (req, res) => {
  res.send(401)
})

//获取客户端真实ip
function getClientIp(req) {
  return req.headers['x-forwarded-for'] ||
  req.connection.remoteAddress ||
  req.socket.remoteAddress ||
  req.connection.socket.remoteAddress;
};

function getLocalIp() {
  try {
    const networkInterface = os.networkInterfaces();
    const NETWORK_CARD_KEY = "WLAN2";
  
    // console.log(10086001, Object.keys(networkInterface));
    // console.log(10086002, networkInterface);
  
    const localNetworkCardInfo = networkInterface[NETWORK_CARD_KEY].find(i => i.family === "IPv4");
    return localNetworkCardInfo.address;
  } catch (error) {
    return "---"
  }
}

function getMimeType(filePath) {
  const defaultMimeType = 'application/octet-stream'
  const extName = path.extname(filePath).toLowerCase()

  const mimeType = {
    '.html': 'text/html',
    '.txt': 'text/plain',
    '.css': 'text/css',
    '.js': 'application/javascript',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf'
  }

  return mimeType[extName] || defaultMimeType
}

app.listen(PORT, () => {
  const ip = getLocalIp();
  console.log('started in address:：', `${ip}:${PORT}`);
});
